import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
// createRouter 创建路由实例，===> new VueRouter()
// history 是路由模式，hash模式，history模式
// createWebHistory() 是开启history模块   http://xxx/user
// createWebHashHistory() 是开启hash模式    http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基准地址，默认是 ’/‘
// https://vitejs.dev/guide/build.html#public-base-path
// 如果将来你部署的域名路径是：http://xxx/my-path/user
// vite.config.ts  添加配置  base: my-path，路由这就会加上 my-path 前缀了
const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import('@/views/Home/index.vue'),
        meta: { title: '首页' }
      },
      {
        path: '/user',
        component: () => import('@/views/User/index.vue'),
        meta: { title: '我的' }
      },
      {
        path: '/article',
        component: () => import('@/views/Article/index.vue'),
        meta: { title: '健康百科' }
      },

      {
        path: '/notify',
        component: () => import('@/views/Notify/index.vue'),
        meta: { title: '消息通知' }
      }
    ]
  },
  {
    path: '/user/patient',
    component: () => import('@/views/User/PatientPage.vue'),
    meta: { title: '家庭档案' }
  },
  {
    path: '/consult/fast',
    component: () => import('@/views/Consult/ConsultFast.vue'),
    meta: { title: '极速问诊' }
  },
  {
    path: '/consult/dep',
    component: () => import('@/views/Consult/ConsultDep.vue'),
    meta: { title: '选择科室' }
  },
  {
    path: '/consult/illness',
    component: () => import('@/views/Consult/ConsultIllness.vue'),
    meta: { title: '病情描述' }
  },
  {
    path: '/consult/pay',
    component: () => import('@/views/Consult/ConsultPay.vue'),
    meta: { title: '问诊支付' }
  },
  {
    path: '/room',
    component: () => import('@/views/Room/index.vue'),
    meta: { title: '问诊室' }
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})
router.beforeEach((to) => {
  document.title = to.meta.title
  // 如果啥也不写，或者return true 就是放行
  // 如果return路由地址就是拦截，然后跳转到当前地址
  const store = useUserStore()
  const whiteList = ['/login']
  // includes判断数组中有没有包含某一项
  if (!store.user?.token && !whiteList.includes(to.path)) return '/login'
})
export default router
